package starter.kit.rx.app.feature.film;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import nucleus.factory.RequiresPresenter;
import starter.kit.feature.NetworkContract;
import starter.kit.feature.rx.RxStarterActivity;
import starter.kit.retrofit.ErrorResponse;
import starter.kit.retrofit.RetrofitException;
import starter.kit.rx.app.R;
import starter.kit.rx.app.model.bean.filmdetail.FilmDetail;
import starter.kit.rx.app.model.bean.filmdetail.FilmPeople;
import starter.kit.rx.app.model.bean.top250.Casts;
import starter.kit.rx.app.model.bean.top250.Directors;
import starter.kit.rx.app.util.DisplayImgUtis;
import starter.kit.rx.app.views.html5.HTML5WebViewActivity;
import support.ui.adapters.EasyRecyclerAdapter;
import work.wanghao.simplehud.SimpleHUD;

import static starter.kit.rx.app.R.id.recyclerview;

/**
 * ============================================================
 * 版权： xx版权所有（c）2016
 * <p>
 * 作者：Loofer
 * 版本：1.0
 * 创建日期 ：2016/10/26 19:10.
 * 描述：
 * <p>
 * 注:如果您修改了本类请填写以下内容作为记录，如非本人操作劳烦通知，谢谢！！！
 * Modified Date Modify Content:
 * <p>
 * ==========================================================
 */
@RequiresPresenter(FilmDetailPresenter.class)
public class FilmDetailActivity extends RxStarterActivity<FilmDetailPresenter> implements NetworkContract.View {


    @BindView(R.id.iv_film)
    ImageView mIvFilm;
    @BindView(R.id.tv_rating)
    TextView mTvRating;
    @BindView(R.id.tv_rating_num)
    TextView mTvRatingNum;
    @BindView(R.id.tv_date_and_film_time)
    TextView mTvDateAndFilmTime;
    @BindView(R.id.tv_film_type)
    TextView mTvFilmType;
    @BindView(R.id.tv_film_country)
    TextView mTvFilmCountry;
    @BindView(R.id.tv_film_name)
    TextView mTvFilmName;
    @BindView(R.id.tv_description)
    TextView mTvDescription;
    @BindView(recyclerview)
    RecyclerView mRecyclerview;
    @BindView(R.id.tv_more_info)
    TextView mTvMoreInfo;
    public static String EXTRA_ID = "id";
    private String mId;//
    private String mAlt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actvity_film_detail);
        Intent intent = getIntent();
        if (intent != null) {
            mId = intent.getStringExtra(EXTRA_ID);
        }
        initView();
    }

    private void initView() {
//        mToolbar.setBackgroundColor(ThemeUtils.getThemeColor());
//        mToolbar.setNavigationIcon(R.drawable.back);
        getPresenter().requestItem(mId);

    }

    @Override
    public void onSuccess(Object item) {
        FilmDetail filmDetail = (FilmDetail) item;
        if (filmDetail.getImages() != null && filmDetail.getImages().getLarge() != null) {
            DisplayImgUtis.getInstance().display(this, filmDetail.getImages().getLarge(), mIvFilm);
        }
        if (!TextUtils.isEmpty(filmDetail.getTitle())) {
            setTitle(filmDetail.getTitle());
        }

        if (filmDetail.getRating() != null) {
            mTvRating.setText("评分" + filmDetail.getRating().getAverage());
        }
        mTvRatingNum.setText(filmDetail.getRatings_count() + "人评分");
        mTvDateAndFilmTime.setText(filmDetail.getYear() + "年  出品");
        if (filmDetail.getCountries() != null && filmDetail.getCountries().size() > 0) {
            mTvFilmCountry.setText(filmDetail.getCountries().get(0));
        }
        if (filmDetail.getGenres() != null && filmDetail.getGenres().size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (String s : filmDetail.getGenres()) {
                stringBuilder.append(s + "/");
            }
            mTvFilmType.setText(stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1));
        }
        mTvDescription.setText(filmDetail.getSummary());
        mTvFilmName.setText(filmDetail.getOriginal_title() + " [原名]");
        initFilmData(filmDetail);
        EasyRecyclerAdapter mAdapter = new EasyRecyclerAdapter(this);
        mAdapter.bind(FilmPeople.class, CastViewHolder.class);
        mRecyclerview.setAdapter(mAdapter);
        mRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        mAdapter.addAll(list);
        mAlt = filmDetail.getAlt();
        mAdapter.setOnClickListener((position, view) -> {
                Intent intent=new Intent(FilmDetailActivity.this, HTML5WebViewActivity.class);
                String alt=list.get(position).getAlt();
                intent.putExtra(HTML5WebViewActivity.EXTRA_URL,alt);
                startActivity(intent);
        });
    }

    @Override
    public void onError(RetrofitException exception) {
        try {
            ErrorResponse errorResponse = exception.getErrorBodyAs(ErrorResponse.class);
            SimpleHUD.showErrorMessage(this, errorResponse.getMessage());
        } catch (IOException e) {
            SimpleHUD.showErrorMessage(this, exception.getMessage());
        }
    }

    private List<FilmPeople> list = new ArrayList<>();

    private void initFilmData(FilmDetail filmDetail) {

        if (filmDetail.getDirectors() != null && filmDetail.getDirectors().size() > 0) {
            for (int i = 0; i < filmDetail.getDirectors().size(); i++) {
                Directors directors = filmDetail.getDirectors().get(i);
                FilmPeople filmPeople = new FilmPeople();

                filmPeople.setAlt(directors.getAlt());
                filmPeople.setAvatars(directors.getAvatars());
                filmPeople.setId(directors.getId());
                filmPeople.setName(directors.getName());
                filmPeople.setType(1);
                list.add(filmPeople);
            }
        }
        if (filmDetail.getCasts() != null && filmDetail.getCasts().size() > 0) {
            for (int i = 0; i < filmDetail.getCasts().size(); i++) {
                Casts casts = filmDetail.getCasts().get(i);
                FilmPeople filmPeople = new FilmPeople();

                filmPeople.setAlt(casts.getAlt());
                filmPeople.setAvatars(casts.getAvatars());
                filmPeople.setId(casts.getId());
                filmPeople.setName(casts.getName());
                filmPeople.setType(2);
                list.add(filmPeople);
            }
        }

    }

    @OnClick({R.id.iv_film, R.id.tv_more_info})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_film:
            case R.id.tv_more_info:
                intent=new Intent(FilmDetailActivity.this, HTML5WebViewActivity.class);
                intent.putExtra(HTML5WebViewActivity.EXTRA_URL,mAlt);
                startActivity(intent);
                break;
        }
    }

}
